from flask import request, render_template, jsonify, redirect, url_for, current_app

from log_analysis import db
from log_analysis.models import BodyData
from log_analysis.modules.data import data_blu


@data_blu.route('/data_calc', methods=["GET", "POST"])
def data_calc():
    """
    人体数据生成
    """
    if request.method == "GET":
        return render_template('data/data_calc.html', data={}, status='true', message='成功!')

    data = request.form
    name = data.get("name")
    height_str = data.get("height")
    weight_str = data.get("weight")

    # 判断数据是否有值
    if not all([name, height_str, weight_str]):
        return render_template("data/data_calc.html", data={}, status="false", message="参数不全!")
    try:
        format(1.23456, '.2f')
        weight = format(float(weight_str), '.3f')
        height = format(float(height_str), '.3f')
    except Exception as e:
        current_app.logger.error(e)
        return render_template("data/data_calc.html", data={}, status="false", message="数据格式错误!")

    # TODO 根据身高,体重生成人体数据

    # 模拟数据: 颈围, 肩宽, 臂围, 臂长, 胸围, 腰围, 臀围, 大腿围, 体型分类
    neck, shoulder_width, arm, arm_length, chest, waist, hip, thigh, shape_type = (
    11.1, 22.2, 33.3, 44.4, 55.5, 66.6, 77.7, 88.8, 1)

    # 初始化人体数据模型，并设置相关数据
    body_data = BodyData()
    body_data.name = name  # 姓名
    body_data.weight = weight  # 身高
    body_data.height = height  # 体重

    body_data.neck = neck  # 颈围
    body_data.shoulder_width = shoulder_width  # 肩宽
    body_data.arm = arm  # 臂围
    body_data.arm_length = arm_length  # 臂长
    body_data.chest = chest  # 胸围
    body_data.waist = waist  # 腰围
    body_data.hip = hip  # 臀围
    body_data.thigh = thigh  # 大腿围
    body_data.shape_type = shape_type  # 体型分类

    # 保存到数据库
    try:
        db.session.add(body_data)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    data = {
        "name": name,
        "height": height,
        "weight": weight,
    }

    result = {
        "neck": neck,
        "shoulder_width": shoulder_width,
        "arm": arm,
        "arm_length": arm_length,
        "chest": chest,
        "waist": waist,
        "hip": hip,
        "thigh": thigh,
        "shape_type": shape_type,
    }
    # print(data, result)
    return render_template('data/data_calc.html', data=data, result=result, status='true', message='成功!')
